package com.pubinfo.passbook.common.utils.financial;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;

@Slf4j
public class CommonTestUtils {
  public static String getRequestParams(String enterId, String privateKey, String password, JSONObject payloadObject) {
    String payload = new BASE64Encoder().encode((JSONObject.toJSONString(payloadObject)).getBytes(StandardCharsets.UTF_8));
    payload = payload.replace("\r\n", "");
    StringBuilder nonce = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < 6; i++) {
      nonce.append(random.nextInt(10));
    }
    long stamp = System.currentTimeMillis() / 1000;
    String dataContent = enterId + payload + stamp + nonce;
    String signature = SignUtil.sign(privateKey, password, dataContent);
    if (signature == null) {
      log.info("签名失败");
      return null;
    }
    JSONObject object = new JSONObject();
    object.put("instCode", enterId);
    object.put("payload", payload);
    object.put("timestamp", stamp);
    object.put("nonce", nonce.toString());
    object.put("signature", signature);
    return object.toJSONString();
  }
  
  public static String post(String url, String json) {
    String obj = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-type", "application/json; charset=utf-8");
    httppost.setHeader("Accept", "application/json");
    try {
      StringEntity s = new StringEntity(json, StandardCharsets.UTF_8);  //对参数进行编码，防止中文乱码
      s.setContentEncoding("UTF-8");
      httppost.setEntity(s);
      try (CloseableHttpResponse response = httpclient.execute(httppost)) {
        //获取相应实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          obj = EntityUtils.toString(entity, "UTF-8");
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return obj;
  }
}
